package com.win.service.impl;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.opencsv.bean.CsvToBeanBuilder;
import com.win.pojo.Happiness;
import com.win.pojo.vo.Useruploadlog;
import com.win.service.HappinessService;
import com.win.mapper.HappinessMapper;
import com.win.service.UseruploadlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
* @author 54478
* @description 针对表【happiness】的数据库操作Service实现
* @createDate 2024-05-20 16:41:54
*/
@Service
public class HappinessServiceImpl extends ServiceImpl<HappinessMapper, Happiness>
    implements HappinessService{
    @Autowired
    private UseruploadlogService logService;
    @Autowired
    private HappinessMapper happinessMapper;

    @Override
    public void importExcelFile(MultipartFile file, String username) throws IOException {
        //获取输入流读取前端发送的文件
        InputStream inputStream = file.getInputStream();
        //读取流中的数据
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        //将读取到的数据封装到集合中
        List<Happiness> tests = reader.readAll(Happiness.class);
        happinessMapper.BatchInsert(tests);

        String uploadFileName = file.getOriginalFilename();
        Useruploadlog log = new Useruploadlog();
        log.setUsername(username);
        log.setFileName(uploadFileName.split("\\.")[0]);
        log.setFileType(uploadFileName.split("\\.")[1]);
        logService.addLog(log);
    }

    @Override
    public void importCSVFile(MultipartFile file, String username) throws IOException {
        //获取输入流读取前端发送的文件
        InputStream inputStream = file.getInputStream();
        List<Happiness> tests = new CsvToBeanBuilder<Happiness>(new InputStreamReader(inputStream))
                .withType(Happiness.class)
                .build()
                .parse();
        happinessMapper.BatchInsert(tests);

        //获取前端上传的文件名称
        String uploadFileName = file.getOriginalFilename();
        Useruploadlog log = new Useruploadlog();
        log.setUsername(username);
        log.setFileName(uploadFileName.split("\\.")[0]);
        log.setFileType(uploadFileName.split("\\.")[1]);
        logService.addLog(log);
    }


}




